package deleteface.bank.jqsoft.cn.deleteface.rsa;

import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public class TestRSA {
    private static final int MAX_ENCRYPT_BLOCK = 117;
    private static final int MAX_DECRYPT_BLOCK = 128;
    public static final String KEY_ALGORITHM = "RSA";
       /**
      63      * RSA加密
      64      *
      65      * @param data 待加密数据
      66      * @param publicKey 公钥
      67      * @return
      68      */
              public static String encrypt(String data, PublicKey publicKey) throws Exception {
               Cipher cipher = Cipher.getInstance("RSA");
               cipher.init(Cipher.ENCRYPT_MODE, publicKey);
               int inputLen = data.getBytes().length;
               ByteArrayOutputStream out = new ByteArrayOutputStream();
                int offset = 0;
             byte[] cache;
                int i = 0;
              // 对数据分段加密
               while (inputLen - offset > 0) {
                    if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                           cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
                            } else {
                               cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
                           }
                        out.write(cache, 0, cache.length);
                        i++;
                         offset = i * MAX_ENCRYPT_BLOCK;
                     }
                 byte[] encryptedData = out.toByteArray();
                 out.close();
               // 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串
                 // 加密后的字符串

                 return new String(Base64Helper.encode(encryptedData));
            }
    /**
     * <p>
     * 公钥加密，进行分片加密，加密大文本
     * </p>
     *
     * @param data 源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(byte[] data, PublicKey publicKey)
            throws Exception {

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

        // 对数据加密
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();

        //String encryptedDataStr = Base64.getEncoder().encodeToString(encryptedData);
//        new String(Base64Helper.encode(encryptedData));

        return new String(Base64Helper.encode(encryptedData));
//        return encryptedData;
    }

    /**
     * <p>
     * 公钥解密，进行分片解密，解密大文本
     * </p>
     *
     * @param encryptedDataStr 已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(byte[] encryptedDataStr, PublicKey publicKey)
            throws Exception {
        //byte[] encryptedData = Base64Helper.decode(encryptedDataStr);
        byte[] encryptedData = encryptedDataStr;
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return new String(decryptedData);
//        return decryptedData;
    }
    /**
     * <p>
     * 公钥解密，进行分片解密，解密大文本
     * </p>
     *
     * @param encryptedDataStr 已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String decryptByPublicKey(String encryptedDataStr, String publicKey)
            throws Exception {
        byte[] encryptedData = Base64Helper.decode(encryptedDataStr);
//        byte[] encryptedData = encryptedDataStr;
        byte[] keyBytes = Base64Helper.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return new String(decryptedData);
//        return decryptedData;
    }


    /**
     * <p>
     * 公钥加密，进行分片加密，加密大文本
     * </p>
     *
     * @param data 源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String encryptByPublicKey(byte[] data, String publicKey)
            throws Exception {
        byte[] keyBytes =Base64Helper.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        String encryptedDataStr=  android.util.Base64.encodeToString(encryptedData, Base64.NO_WRAP);
//        String encryptedDataStr = Base64Helper.encode(encryptedData);
        return encryptedDataStr;
    }



}
